import { useState } from 'react'

const useChangeList = ({
  initListData
}) => {

  const [listData, setListData] = useState(initListData)

  const handleCreate = () => {

  }

  const handleInsert = () => {

  }

  const handleModify = (rowData, index) => {
    setListData((_listData) => {
      const _newListData = _listData.map((el, i) => {
        if (i === index) {
          return rowData
        } else {
          return el
        }
      })
      return _newListData
    })
  }

  const handleModifyField = (key, val, index) => {
    setListData((_listData) => {
      const _newListData = _listData.map((el, i) => {
        if (i === index) {
          return {
            ...el,
            [key]: val
          }
        } else {
          return el
        }
      })
      return _newListData
    })
  }

  const handleDelete = (index) => {
    setListData((_listData) => {
      const _newListData = _listData.filter((el, i) => i !== index)
      return _newListData
    })
  }

  const handleMove = (fromIndex, toIndex) => {
    setListData((_listData) => {
      const _newListData = _listData.map((el, i) => {
        switch (i) {
          case fromIndex:
            return listData[toIndex]
          case fromIndex:
            return listData[toIndex]
          default:
            return el
        }
      })
      return _newListData
    })
  }

  return {
    handleCreate,
    handleInsert,
    handleModify,
    handleModifyField,
    handleDelete,
    handleMove,
    listData
  }
}

export default useChangeList